package com.zaofan.mobile.controller;

import com.zaofan.bean.Account;
import com.zaofan.bean.AccountFrom;
import com.zaofan.exception.ServiceException;
import com.zaofan.service.AccountFromService;
import com.zaofan.service.AccountService;
import com.zaofan.service.remote.RemoteService;
import com.zaofan.utils.IdWorker;
import com.zaofan.utils.JedisUtils;
import com.zaofan.utils.JsonUtils;
import com.zaofan.utils.WebUtils;
import com.zaofan.utils.pay.MD5Util;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/mobile/user")
public class UserController extends BaseServlet {

	private static final long serialVersionUID = 5884947841079014459L;
	private AccountService accountService = new AccountService();
	private AccountFromService accountFromService =new AccountFromService();
	private RemoteService remoteService = new RemoteService();
	private static final Logger logger = LoggerFactory.getLogger(UserController.class);


	//-----------------------手机验证码快捷登录--------------------------------

	protected void quickMobileLogin(HttpServletRequest request,
									HttpServletResponse response) throws ServletException,IOException{

		try {
			Account account = WebUtils.write2bean(request, Account.class);

			Map bm = new HashMap();
			Map<String, String[]> tmp = request.getParameterMap();
			if (tmp != null) {
				for (String key : tmp.keySet()) {
					String[] values = tmp.get(key);
					bm.put(key, values.length == 1 ? values[0].trim() : values);
				}
			}
			String sign = (String) bm.get("sign");
			logger.info("快捷登录传过来的SIGN-------："+sign);

			bm.remove("sign");
			String sign1 = WebUtils.getSignature(bm,WebUtils.appSecret);
			logger.info("快捷登录生成的sign1---------："+sign1);

			if (!sign.equals(sign1)){
				JsonUtils.writeBeanFailJson("提交参数错误", response);
				return;
			}


			String code = request.getParameter("code");

			String cacheCode = JedisUtils.get("quickMobileCode_" + account.getMobile());
			if (cacheCode == null) {
				JsonUtils.writeBeanFailJson("验证码过期,请重试!!", response);
				return;
			}
			if (!code.equals(cacheCode)) {
				JsonUtils.writeBeanFailJson("验证码错误,请重试!!", response);
				return;
			}

			//先判断是否有这个账号,如果没有的话,生成一个随机密码的账号
			Account account1 = accountService.findByMobile(account.getMobile());
			if(account1 == null && account.getCityId() == 0){
				JsonUtils.writeFailJson("请选择城市",response);
				return ;
			}
			Account quickAccount = accountService.quickCodeLogin(account);

//			注册时间
			request.getSession().setAttribute("user", quickAccount);
			com.zaofan.mobile.bean.Account a = new com.zaofan.mobile.bean.Account();
			BeanUtils.copyProperties(a, quickAccount);
			request.getSession().removeAttribute("code");
			System.err.println("quickLogin : " + quickAccount.getMobile());
			String userSign = MD5Util.MD5Encode(IdWorker.nextId(""), "utf-8");
			JedisUtils.set("userSign_" + a.getId(), userSign);
			a.setUserSign(userSign);
//			remoteService.recordQRCodeId(request.getParameter("QRCodeId"), quickAccount);
			request.getSession().setAttribute("userinfo",a);
			if(account1 == null){
				JsonUtils.writeSuccessJson("注册成功", a, response);
			}else {
				JsonUtils.writeSuccessJson("登录成功", a, response);
			}
			return;
		} catch (ServiceException service) {
			JsonUtils.writeFailJson(service.getMessage(), response);
			return;
		} catch (Exception e) {
			e.printStackTrace();
			JsonUtils.writeBeanFailJson("登录失败!!" + e.getMessage(), response);
		}
		JsonUtils.writeBeanFailJson("登录失败!!" + ",未知错误", response);
	}

	/**
	 *
	 * 手机快捷登录验证码接口
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
     */
	protected void quickMobileCode(HttpServletRequest request,
								   HttpServletResponse response) throws ServletException,IOException{
		try {
			String mobile = request.getParameter("mobile");
			String code = WebUtils.getRandonNum(6);
			accountService.sendQuickMobileCode(mobile, code);
			request.getSession().setAttribute("code", code);
			request.getSession().setAttribute("mobile", mobile);
			System.err.println("quick mobile code : " + mobile + " , code : " + code);
			JedisUtils.setex("quickMobileCode_" + mobile, 60 * 15, code);
			Account account = accountService.findByMobile(mobile);
			if(account == null){
				JsonUtils.writeSuccessJson("发送成功",false, response);
			}else{
				JsonUtils.writeSuccessJson("发送成功",true, response);

			}
			return;
		} catch (ServiceException service) {
			JsonUtils.writeFailJson(service.getMessage(), response);
			return;
		} catch (Exception e) {
			e.printStackTrace();
			if (e.getMessage() != null && !"".equals(e.getMessage())) {
				JsonUtils.writeFailJson(e.getMessage(), response);
			} else {
				JsonUtils.writeFailJson("发送失败", response);
			}
		}
		JsonUtils.writeFailJson("发送失败", response);
	}

	//----------------------------------------------------------------
	/**
	 * userSign失效的测试接口
	 * 
	 */
	protected void userSignTest(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		JsonUtils.writeBeanFailJson("登录失效, 请重新登录", 6002,response);
	}
	
	
	/**
	 * 用户登录接口
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void login(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			Account account = WebUtils.write2bean(request, Account.class);
			Account acc = accountService.login(account);
			com.zaofan.mobile.bean.Account target = accountService.findAccountInfo(acc.getId());
			logger.info("登录用户信息: {}", target);
            request.getSession().setAttribute("userinfo",target);
//            String host = request.getServerName();
            Cookie cookie = new Cookie("JSESSIONID", request.getSession().getId()); // 保存用户名到Cookie
            cookie.setPath("/");
//            cookie.setDomain(host);
            cookie.setMaxAge(60*60*24*7);
            response.addCookie(cookie);
			String userSign = MD5Util.MD5Encode(IdWorker.nextId(""), "utf-8");
			JedisUtils.set("userSign_" + target.getId(), userSign);
			target.setUserSign(userSign);
			JsonUtils.writeSuccessJson("登录成功", target, response);
			return;
		} catch (ServiceException service) {
			JsonUtils.writeFailJson(service.getMessage(), response);
			return;
		} catch (Exception e) {
			e.printStackTrace();
			JsonUtils.writeBeanFailJson("登录失败!!" + e.getMessage(), response);
		}
		JsonUtils.writeBeanFailJson("登录失败!!" + ",未知错误", response);
	}

	/**
	 * 注册 验证码接口
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void code(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			String mobile = request.getParameter("mobile");
			String code = WebUtils.getRandonNum(6);
			accountService.sendRegisterCode(mobile, code);
			request.getSession().setAttribute("code", code);
			JedisUtils.setex("registerCode_" + mobile, 60 * 15, code);
			request.getSession().setAttribute("mobile", mobile);
			System.err.println("register send code : " + code);
			JsonUtils.writeSuccessJson("发送成功", "", response);
			return;
		} catch (ServiceException service) {
			JsonUtils.writeFailJson(service.getMessage(), response);
			return;
		} catch (Exception e) {
			e.printStackTrace();
			JsonUtils.writeFailJson("发送失败", response);
		}
		JsonUtils.writeFailJson("发送失败", response);
	}
	
	
	/**
	 * 注册 验证码接口
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void code2(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			String mobile = request.getParameter("mobile");
			String code = WebUtils.getRandonNum(6);
			accountService.sendRegisterCode(mobile, code);
			JedisUtils.setex("registerCode_" + mobile, 60 * 15, code);
			JsonUtils.writeSuccessJson("发送成功", "", response);
			return;
		} catch (ServiceException service) {
			JsonUtils.writeFailJson(service.getMessage(), response);
			return;
		} catch (Exception e) {
			e.printStackTrace();
			JsonUtils.writeFailJson("发送失败", response);
		}
		JsonUtils.writeFailJson("发送失败", response);
	}
	
	
	/**
	 * 用户注册接口
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void register(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			Account account = WebUtils.write2bean(request, Account.class);
			String code = request.getParameter("code");
			String cityId = request.getParameter("cityId");
			String old =(String) request.getSession().getAttribute("code");
			String mobile = (String) request.getSession().getAttribute("mobile");

			System.out.println(mobile+"第一次的mobile");
			if (code == null) {
				JsonUtils.writeBeanFailJson("请填写正确的验证码!!", response);
				return;
			}
			if (cityId == null) {
				JsonUtils.writeBeanFailJson("请先选择城市!!", response);
				return;
			}
			if (old == null) {
				JsonUtils.writeBeanFailJson("验证码过期,请重试!!", response);
				return;
			}
			if (!code.equals(old)) {
				JsonUtils.writeBeanFailJson("验证码错误,请重试!!", response);
				return;
			}
			System.out.println("第二次获得mobile"+account.getMobile());
			if (!mobile.equals(account.getMobile())) {
				JsonUtils.writeBeanFailJson("手机号码不一致,请重试!!", response);
				return;
			}



			Account acc = accountService.register(account);
			request.getSession().setAttribute("user", acc);
			com.zaofan.mobile.bean.Account a = new com.zaofan.mobile.bean.Account();
			BeanUtils.copyProperties(a, acc);
			request.getSession().removeAttribute("code");
			System.err.println("register : " + acc.getMobile());
			String userSign = MD5Util.MD5Encode(IdWorker.nextId(""), "utf-8");
			JedisUtils.set("userSign_" + a.getId(), userSign);
			a.setUserSign(userSign);
			request.getSession().setAttribute("userinfo",a);

			String from = "";
			if(null==request.getParameter("from")||"".equals(request.getParameter("from"))){
				from="";
			}else{
				//记录平台
				from=request.getParameter("from");
				AccountFrom  accountFrom= new AccountFrom();
				accountFrom.setFromType(from);
				accountFrom.setMobile(mobile);
				logger.info("添加记录第三方平台");
				accountFromService.add(accountFrom);
			}


			//记录二维码人员
			logger.info("添加记录二维码");
			remoteService.recordQRCodeId(request.getParameter("QRCodeId"), acc);
			JsonUtils.writeSuccessJson("注册成功", a, response);

			return;
		} catch (ServiceException service) {
			JsonUtils.writeFailJson(service.getMessage(), response);
			return;
		} catch (Exception e) {
			e.printStackTrace();
			JsonUtils.writeBeanFailJson("注册失败!!" + e.getMessage(), response);
		}
		JsonUtils.writeBeanFailJson("注册失败!!" + ",未知错误", response);
	}

	/**
	 * 安卓注册。。
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void register1(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			Account account = WebUtils.write2bean(request, Account.class);
			Account acc = accountService.register(account);
			request.getSession().setAttribute("user", acc);
			com.zaofan.mobile.bean.Account a = new com.zaofan.mobile.bean.Account();
			BeanUtils.copyProperties(a, acc);
			request.getSession().removeAttribute("code");
			System.err.println("register1 : " + acc.getMobile());
			String userSign = MD5Util.MD5Encode(IdWorker.nextId(""), "utf-8");
			JedisUtils.set("userSign_" + a.getId(), userSign);
			a.setUserSign(userSign);
			remoteService.recordQRCodeId(request.getParameter("QRCodeId"), acc);
			request.getSession().setAttribute("userinfo",a);
			JsonUtils.writeSuccessJson("注册成功", a, response);
			return;
		} catch (ServiceException service) {
			JsonUtils.writeFailJson(service.getMessage(), response);
			return;
		} catch (Exception e) {
			e.printStackTrace();
			JsonUtils.writeBeanFailJson("注册失败!!" + e.getMessage(), response);
		}
		JsonUtils.writeBeanFailJson("注册失败!!" + ",未知错误", response);
	}
	
	
	protected void register2(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {




		try {
			Account account = WebUtils.write2bean(request, Account.class);


			String platform = request.getParameter("platform");
			String appVersion = request.getParameter("appVersion");

			Map bm = new HashMap();
			Map<String, String[]> tmp = request.getParameterMap();
			if (tmp != null) {
				for (String key : tmp.keySet()) {
					String[] values = tmp.get(key);
					bm.put(key, values.length == 1 ? values[0].trim() : values);
				}
			}
			String sign = (String) bm.get("sign");
			logger.info("传过来的SIGN-------："+sign);

			bm.remove("sign");
			String sign1 = WebUtils.getSignature(bm,WebUtils.appSecret);
			logger.info("生成的sign1---------："+sign1);

			if (!sign.equals(sign1)){
				JsonUtils.writeBeanFailJson("提交参数错误", response);
				return;
			}


			String code = request.getParameter("code");



			String old = JedisUtils.get("registerCode_" + account.getMobile());
			if (old == null) {
				JsonUtils.writeBeanFailJson("验证码过期,请重试!!", response);
				return;
			}
			if (!code.equals(old)) {
				JsonUtils.writeBeanFailJson("验证码错误,请重试!!", response);
				return;
			}
//			注册时间
			Account acc = accountService.register(account);
			request.getSession().setAttribute("user", acc);
			com.zaofan.mobile.bean.Account a = new com.zaofan.mobile.bean.Account();
			BeanUtils.copyProperties(a, acc);
			request.getSession().removeAttribute("code");
			System.err.println("register2 : " + acc.getMobile());
			String userSign = MD5Util.MD5Encode(IdWorker.nextId(""), "utf-8");
			JedisUtils.set("userSign_" + a.getId(), userSign);
			a.setUserSign(userSign);
			request.getSession().setAttribute("userinfo",a);
			JsonUtils.writeSuccessJson("注册成功", a, response);
			return;
		} catch (ServiceException service) {
			JsonUtils.writeFailJson(service.getMessage(), response);
			return;
		} catch (Exception e) {
			e.printStackTrace();
			JsonUtils.writeBeanFailJson("注册失败!!" + e.getMessage(), response);
		}
		JsonUtils.writeBeanFailJson("注册失败!!" + ",未知错误", response);
	}
	

	/**
	 * 找回密码 验证码接口
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void findCode(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			String mobile = request.getParameter("mobile");
			String code = WebUtils.getRandonNum(6);
			accountService.sendFindCode(mobile, code);
			request.getSession().setAttribute("code", code);
			request.getSession().setAttribute("mobile", mobile);
			System.err.println("find password code : " + mobile + " , code : " + code);
			JsonUtils.writeSuccessJson("发送成功",code, response);
			return;
		} catch (ServiceException service) {
			JsonUtils.writeFailJson(service.getMessage(), response);
			return;
		} catch (Exception e) {
			e.printStackTrace();
			if (e.getMessage() != null && !"".equals(e.getMessage())) {
				JsonUtils.writeFailJson(e.getMessage(), response);
			} else {
				JsonUtils.writeFailJson("发送失败", response);
			}
		}
		JsonUtils.writeFailJson("发送失败", response);
	}
	
	/**
	 * 找回密码 验证码接口
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void findCode2(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			String mobile = request.getParameter("mobile");
			String code = WebUtils.getRandonNum(6);
			accountService.sendFindCode(mobile, code);
			JedisUtils.setex("findCode2_" + mobile, 60*15, code);
			JsonUtils.writeSuccessJson("发送成功", "", response);
			return;
		} catch (ServiceException service) {
			JsonUtils.writeFailJson(service.getMessage(), response);
			return;
		} catch (Exception e) {
			e.printStackTrace();
			if (e.getMessage() != null && !"".equals(e.getMessage())) {
				JsonUtils.writeFailJson(e.getMessage(), response);
			} else {
				JsonUtils.writeFailJson("发送失败", response);
			}
		}
		JsonUtils.writeFailJson("发送失败", response);
	}
	

	/**
	 * 找回密码 修改密码
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void resetPass(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			Account account = WebUtils.write2bean(request, Account.class);
			accountService.resetPass(account);
			System.err.println("find password code : " + account.getMobile());
//			JedisUtils.del("userSign_" + account.getId());
			JsonUtils.writeSuccessJson("修改成功", "", response);
			return;
		} catch (ServiceException service) {
			JsonUtils.writeFailJson(service.getMessage(), response);
			return;
		} catch (Exception e) {
			e.printStackTrace();
			JsonUtils.writeFailJson("修改失败", response);
		}
		JsonUtils.writeFailJson("修改失败", response);
	}
	
	protected void resetPass2(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			Account account = WebUtils.write2bean(request, Account.class);
			String code = request.getParameter("code");
			String redisCode = JedisUtils.get("findCode2_" + account.getMobile());
			if (redisCode == null) {
				JsonUtils.writeBeanFailJson("验证码过期,请重试!!", response);
			}
			if (!redisCode.equals(code)) {
				JsonUtils.writeBeanFailJson("验证码错误,请重试!!", response);
			}
			accountService.resetPass(account);
			JedisUtils.del("userSign_" + account.getId());
			JsonUtils.writeSuccessJson("修改成功", "", response);
			return;
		} catch (ServiceException service) {
			JsonUtils.writeFailJson(service.getMessage(), response);
			return;
		} catch (Exception e) {
			e.printStackTrace();
			JsonUtils.writeFailJson("修改失败", response);
		}
		JsonUtils.writeFailJson("修改失败", response);
	}

	/**
	 * 修改密码
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void modifyPass(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			String id = request.getParameter("id");
			String old = request.getParameter("old");
			String password = request.getParameter("password");
			accountService.modifyPass(id, old, password);
			System.err.println("modify password code : " + id);
			JedisUtils.del("userSign_" + id);
			JsonUtils.writeSuccessJson("修改成功", "", response);
			return;
		} catch (ServiceException service) {
			JsonUtils.writeFailJson(service.getMessage(), response);
			return;
		} catch (Exception e) {
			e.printStackTrace();
			JsonUtils.writeFailJson("修改失败,", response);
		}
		JsonUtils.writeFailJson("修改失败", response);
	}

	/**
	 * 用户信息
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void info(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			String temp = request.getParameter("id");
			int id = Integer.valueOf(temp);
			com.zaofan.mobile.bean.Account account = accountService.findAccountInfo(id);
			if (account == null) {
				JsonUtils.writeBeanFailJson("参数错误", response);
				return;
			}
			JsonUtils.writeSuccessJson("查询成功", account, response);
			return;
		} catch (Exception e) {
			e.printStackTrace();
			JsonUtils.writeBeanFailJson("参数错误", response);
		}
		JsonUtils.writeBeanFailJson("获取失败", response);
	}

	/**
	 * 用户修改资料
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void update(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			Account account = WebUtils.write2bean(request, Account.class);
			accountService.updateAccountInfo(account);
			System.err.println("update info : id = " + account.getMobile());
			com.zaofan.mobile.bean.Account acc = accountService.findAccountInfo(account.getId());
            request.getSession().setAttribute("userinfo",acc);
			JsonUtils.writeSuccessJson("修改成功", acc, response);
			return;
		} catch (ServiceException service) {
			JsonUtils.writeFailJson(service.getMessage(), response);
			return;
		} catch (Exception e) {
			e.printStackTrace();
			JsonUtils.writeBeanFailJson("修改失败", response);
		}
		JsonUtils.writeBeanFailJson("修改失败", response);
	}

	protected void photo(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			Account user = fileUploadHanderUserPhoto(request);
			Account target = accountService.findById(user.getId());
			if (target == null || target.getPhoto() == null) {
				JsonUtils.writeFailJson("参数错误!!", response);
				return;
			}
			target.setPhoto(user.getPhoto());
			System.err.println("update photo : url = " + user.getPhoto());
			accountService.update(target);
			com.zaofan.mobile.bean.Account acc = accountService.findAccountInfo(target.getId());
            request.getSession().setAttribute("userinfo",acc);
			JsonUtils.writeSuccessJson("操作成功!!", acc, response);
		} catch (Exception e) {
			JsonUtils.writeBeanFailJson("参数错误!!", response);
		}
		JsonUtils.writeBeanFailJson("操作失败!!", response);
	}

	private Account fileUploadHanderUserPhoto(HttpServletRequest request) {
		List<String> allowType = Arrays.asList("image/bmp","image/png","image/gif","image/jpg","image/jpeg","image/pjpeg");  
		List<String> allowSuffix = Arrays.asList(".png",".gif",".jpg",".jpeg",".pjpeg");  
		Map<String, String> mFileTypes = new HashMap<String, String>();
		mFileTypes.put("FFD8FFE0", ".jpg");
        mFileTypes.put("89504E47", ".png");
        mFileTypes.put("47494638", ".gif");
		Account user = new Account();
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setHeaderEncoding("utf-8");
		String random = new Random().nextInt() + "";
		try {
			List<FileItem> items = upload.parseRequest(request);
			for (FileItem item : items) {
				if (item.isFormField()) {
					String value = new String(item.getString().getBytes("ISO8859-1"), "UTF-8");
					String key = item.getFieldName();
					BeanUtils.setProperty(user, key, value);
					System.out.println(key + " = " + value);
				} else {
					if (!allowType.contains(item.getContentType()) || !allowSuffix.contains(item.getName().substring(item.getName().lastIndexOf(".")).toLowerCase())) {
						logger.info("item.getContentType: {}, item.getName: {}", item.getContentType(), item.getName());
						return user;
					}
					InputStream in = item.getInputStream();
					String path = WebUtils.makeDir(this.getServletContext().getRealPath("/user_photo"), random + "")
							+ "/" + WebUtils.getUUID() + "_" + random
							+ item.getName().substring(item.getName().lastIndexOf("."));
					FileOutputStream out = new FileOutputStream(
							this.getServletContext().getRealPath("/user_photo") + "/" + path);
					BufferedOutputStream bos = new BufferedOutputStream(out);
					int len = 0;
					byte[] buff = new byte[1024];
					byte[] type = new byte[4];
					len = in.read(type);
					if (mFileTypes.containsKey(bytesToHexString(type).toUpperCase())) {
						bos.write(type, 0, len);
					} else {
						logger.info("文件类型不是图片：{}", item.getName());
						bos.close();
						return user;
					}
					
					while ((len = in.read(buff)) != -1) {
						bos.write(buff, 0, len);
					}
					bos.close();
					user.setPhoto("/user_photo/" + path);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return user;
	}
	
    private static String bytesToHexString(byte[] src) {
        StringBuilder builder = new StringBuilder();
        if (src == null || src.length <= 0) {
            return null;
        }
        String hv;
        for (int i = 0; i < src.length; i++) {
            // 以十六进制（基数 16）无符号整数形式返回一个整数参数的字符串表示形式，并转换为大写
            hv = Integer.toHexString(src[i] & 0xFF).toUpperCase();
            if (hv.length() < 2) {
                builder.append(0);
            }
            builder.append(hv);
        }
         
        System.out.println("获取文件头信息:"+builder.toString());
         
        return builder.toString();
    }

}
